<?php

namespace app\common\controller;


/**
 * 二维码生成
 * Class Code
 * @package app\common\controller
 */
class Wxcode extends Wechat
{


    /**
     * @return 小程序二维码
     */
    public function getWxcode($uid){
        header("Content-type:image/jpg");
        // 获取小程序access_token
        $access_token = $this->get_access_token();
        $url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$access_token";
        $post_data = array(
            'page'=>'pages/index/index',// 用户扫码进去的页面
            'auto_color'=>true,// 二维码颜色随机
            'width' => 400,// 二维码大小
            'scene'=>$uid, //这是二维码携带的参数
            'is_hyaline'=>true// 二维码透明
        );
        // 生成的图片名称
        $codename = $uid.".jpg";
        $post_data=json_encode($post_data);
        $data = $this->send_post($url,$post_data);
        // 展示二维码
        //$result=$this->data_uri($data,'image/jpg');
        //echo "<img src='$result'>";die;
        // 获取绝对路径
        $path = $this->request->server()['DOCUMENT_ROOT']."/uploads/code/";
        // 写入文件
        file_put_contents($path.$codename,$data);
        // 返回的二维码路径
        $codeimg = $this->request->domain().'/uploads/code/'.$codename;
        return $codeimg;
    }





    /**
     * 消息推送http
     * @param $url
     * @param $post_data
     * @return bool|string
     */
    protected function send_post( $url, $post_data ) {
        $options = array(
            'http' => array(
                'method'  => 'POST',
                'header'  => 'Content-type:application/json',
                //header 需要设置为 JSON
                'content' => $post_data,
                'timeout' => 60
                //超时时间
            )
        );
        $context = stream_context_create( $options );
        $result = file_get_contents( $url, false, $context );
        return $result;
    }

    //二进制转图片image/png
    protected function data_uri($contents, $mime)
    {
        $base64  = base64_encode($contents);

        return ('data:' . $mime . ';base64,' . $base64);

    }


    /**
     * 创建公众号二维码ticket
     */
    public function ticket($id=null){
        //获取公众号 access_token
        $public_access_token = $this->public_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$public_access_token";
        $post_data = [
            'action_name'=>'QR_LIMIT_STR_SCENE',  // 二维码类型
            'action_info' => [          //二维码详细信息
                'scene'=>[              //二维码参数
                    "scene_str"=> 'xq-'.$id //自定义参数(小区-id)
                ]
            ]
        ];
        $post_data = json_encode($post_data);
        $data = $this->send_post($url,$post_data);
        $data = json_decode($data,true);
        //写入参数
        //file_put_contents('ticket.txt', json_encode($data));
        $res = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$data['ticket'];
        return $res;
    }

}


